﻿using Furion;
using HiSport.Core;
using HiSport.Core.Const;
using HiSport.Core.Entity;
using HiSport.Core.Enum;
using HiSport.Core.Options;
using Microsoft.AspNetCore.Identity;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace HiSport.SqlSugar
{
    /// <summary>
    /// SqlSugar 实体仓储
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public class SqlSugarRepository<T> : SimpleClient<T> where T : class, new()
    {
        protected ITenant iTenant = null;

        public SqlSugarRepository(ISqlSugarClient context = null) : base(context)
        {
            iTenant = App.GetRequiredService<ISqlSugarClient>().AsTenant();

            // 若实体贴有多库特性，则返回指定库连接
            if (typeof(T).IsDefined(typeof(TenantAttribute), false))
            {
                base.Context = iTenant.GetConnectionScopeWithAttr<T>();
                return;
            }

            // 若实体贴有日志表特性，则返回日志库连接
            if (typeof(T).IsDefined(typeof(LogTableAttribute), false))
            {
                base.Context = iTenant.IsAnyConnection(SqlSugarConst.ConfigId)
                    ? iTenant.GetConnectionScope(SqlSugarConst.ConfigId)
                    : iTenant.GetConnectionScope(SqlSugarConst.MainConfigId);
                return;
            }

            // 若实体贴有系统表特性，则返回默认库连接
            if (typeof(T).IsDefined(typeof(SysTableAttribute), false))
            {
                base.Context = iTenant.GetConnectionScope(SqlSugarConst.MainConfigId);
                return;
            }

            // 若未贴任何表特性或当前未登录或是默认租户Id，则返回默认库连接
            var tenantId =CurrentUser.TenantId;
            if (tenantId < 1 || tenantId.ToString() == SqlSugarConst.MainConfigId) return;

            // 若租户为空或租户以Id隔离模式时，则返回默认库连接
            var tenant = App.GetRequiredService<SysCacheService>().Get<List<SysTenant>>(CacheConst.KeyTenant).FirstOrDefault(u => u.Id == tenantId);
            if (tenant is null) return;

            // 若租户以库隔离模式时，根据租户Id切换库连接
            if (!iTenant.IsAnyConnection(tenantId.ToString()))
            {
                // 获取默认库连接配置
                var dbOptions = App.GetOptions<DbConnectionOptions>();
                var mainConnConfig = dbOptions.ConnectionConfigs.First(u => u.ConfigId == SqlSugarConst.MainConfigId);

                // 设置租户库连接配置
                var tenantConnConfig = new DbConnectionConfig
                {
                    ConfigId = tenant.Id,
                    DbType = tenant.DbType,
                    IsAutoCloseConnection = true,
                    ConnectionString = tenant.ConnectionString,
                    DbSettings = new DbSettings()
                    {
                        EnableUnderLine = mainConnConfig.DbSettings.EnableUnderLine,
                    }
                };
                iTenant.AddConnection(tenantConnConfig);
                SqlSugarSetup.SetDbConfig(tenantConnConfig);
                SqlSugarSetup.SetDbAop(iTenant.GetConnectionScope(tenantId.ToString()), dbOptions.EnableConsoleSql);
            }
            base.Context = iTenant.GetConnectionScope(tenantId.ToString());
        }
    }
}
